package com.adtec.base.cloud.server.gateway.config;

import com.adtec.base.cloud.server.gateway.filter.handler.GlobalLogFilter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.reactive.CorsWebFilter;
import org.springframework.web.cors.reactive.UrlBasedCorsConfigurationSource;
import org.springframework.web.util.pattern.PathPatternParser;

import java.util.Arrays;

@Configuration
public class GlobalGatewayFilterConfig {
//    @Bean
//    @Order(-100)
//    public GlobalFilter apiGlobalFilter() {
//        return (exchange, chain) -> {
//            //获取请求处理之前的时间
//            Long startTime = System.currentTimeMillis();
//            //请求处理完成之后
//            return chain.filter(exchange).then().then(Mono.fromRunnable(() -> {
//                //获取请求处理之后的时间
//                Long endTime = System.currentTimeMillis();
//                //这里可以将结果进行持久化存储，我们暂时简单处理打印出来
//                System.out.println(
//                        exchange.getRequest().getURI().getRawPath() +
//                                ", cost time : "
//                                + (endTime - startTime) + "ms");
//            }));
//        };
//    }

    /**
     * 全局过滤器：请求日志打印
     */
    @Bean
    public GlobalLogFilter globalLogFilter(){
        // 该值越小权重却大，所以应根据具体项目配置。需要尽早的获取到参数，一般会是一个比较小的值
        return new GlobalLogFilter(-20);
    }


    @Bean
    public CorsWebFilter corsFilter() {
        CorsConfiguration config = new CorsConfiguration();
        config.setAllowedMethods(Arrays.asList(
                HttpMethod.POST.name(),
                HttpMethod.GET.name()
        ));
//        config.addAllowedOrigin("Http://localhost:8081");
        config.addAllowedOrigin("*");
        config.addAllowedHeader("*");
        config.addAllowedMethod("*"); // 允许任何方法（post、get等）

        UrlBasedCorsConfigurationSource source
                = new UrlBasedCorsConfigurationSource(new PathPatternParser());
        source.registerCorsConfiguration("/**", config);

        return new CorsWebFilter(source);
    }
}